<?php
namespace app\common\controller;
use think\Controller;
use think\Config;
use think\Loader;
use think\Request;
use think\Db;
class App extends Controller{
	public $file,$files,$params,$args,$absroot,$root,$assign,$appid,$secret; 
	//哪些控制器不用验证
	public $notLogin = array('login');

	public function _initialize(){
		 
		//获取URL参数
		$passedArgs     = input('') ;
		//获取当前模块、控制器、方法
		$request = Request::instance();
		//当前访问参数
		$this->params = array(
			'module' =>$request->module(),
			'controller' =>$request->controller(),
			'action' =>$request->action(),
			'module' =>$request->module(),
			'args' =>$passedArgs
		);
		//当前URL参数
		$this->args   =    $passedArgs ; 
		//IIS编码修正
	    if(strpos($_SERVER['SERVER_SOFTWARE'],'Microsoft-IIS')!==false){            
			foreach($this->passedArgs as &$passedArg){
				$passedArg    = mb_convert_encoding($passedArg,'UTF-8','GBK');
			}
		} 
		switch (strtolower($this->params['module'])) {
			//前台
			case 'index':
					$appid = $this->appid=Config::get('APPID');
					$secret = $this->secret=Config::get('APPSECRET');
					$token  = cache('Token');

					if(!$token['access_token'] || $token['expires_in'] <= time()){
						$rslt  = gets("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}");
						if($rslt){
							$accessArr = array(
								'access_token'=>$rslt['access_token'],
								'expires_in'=>time()+$rslt['expires_in']-200
							);
							cache('Token',$accessArr) ;
							$token = $rslt;
						}
					} 
					if(!session('MEMBER')){
				
						##没有登录
						##如果没有登录，我们要让url地址跳转到 微信url 去获取code
						$myurl =  urlencode('https://driver.junyiqiche.com/wechat/Wechat/adduser');//mvc : http://wx4.cdphm.net/User/wxlogin  ##微信回调地址（这个地址是我们自己的一个url地址，必须使用urlencode处理）
						$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$myurl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
						header('Location:'.$url);
						die();
					} 
				break;
			//后台
		 	case 'run':
		  
			// dump(strtolower($this->params['controller']));die;
			if(!session('?ADMIN_USER')&& !in_array(strtolower($this->params['controller']),$this->notLogin)){
				// echo 1;die;
				$this->redirect('run/Login/login');
			} 
			//公用css

		 	
				break;
		}
		 //当前相对根域名
		 $this->root     =__ROOT__;
		 
		 if(substr($this->root,0,8) =='/wwwroot') $this->root = substr($this->root,8);
		 
		 
		 //当前绝对根域名 $this->absroot = 项目目录/public
		 $this->absroot= $request->domain().$request->root();
		  
		 
		 $absrootArray = explode('/',$this->absroot);

		 if(end($absrootArray) == 'index.php'){
		     array_pop($absrootArray);
		     $this->absroot = implode('/',$absrootArray);
		 }
		 
		 
		$this->assign('static',$this->absroot.'/static/');
		$this->assign('admin',$this->absroot.'/static/admin/');
		$this->assign('index',$this->absroot.'/static/index/');
		$this->assign('root',$this->root) ;
 		$this->assign('absroot',$this->absroot.'/') ;	
 		$this->assign('rootpath',ROOT_PATH);
		//判断当前是否通过手机端访问
		// $this->isMobile =  $this->assign->isMobile =   $this->request->isMobile();
		        
		//当前服务器时间  
		// $this->now      =  $this->assign->now =  time();  
		##重写assign方法，统一管理，让变量传出都通过我们自己的Assign对象传出



	}
 
		 
		
		 

	function addJs($file){
	    if(substr($file,0,1) != '/' && !preg_match('/^http:\/\//' ,$file)){
	       
	        $file ='/js/'.$file;
	         
	    }
	    if(!preg_match('/^http:\/\//' ,$file)){
	        $file = 'static'.$file;
	       
	    }        
	    if(strtolower(substr($file,-3)) !='.js'){
	        $file .= '.js'; 
	    } 
	    
	    $this->file['js'][]= $file ;
	    
	    
	}

	function addCss($files){
	    if(substr($files,0,1) != '/' && !preg_match('/^http:\/\//' ,$files)){
	        $files ='/css/'.$files;
	    }
	    if(!preg_match('/^http:\/\//' ,$files)){
	        $files = 'static'.$files;
	    }        
	    if(strtolower(substr($files,-3)) !='.css'){
	        $files .= '.css'; 
	    }
	    $this->files['css'][] = $files ;        
	}
	//重写fetch方法
	protected function fetch($templateFile='',$charset='',$contentType='',$content='',$prefix='') {
	    
	    $this->assign('params',$this->params);
	    $this->assign('js',$this->file['js']);
	    $this->assign('css',$this->files['css']);
	    return call_user_func_array(array('parent',__FUNCTION__),func_get_args());
	}
	
	##表单自动验证
	protected function auto_proof($data){
	    $rule = [
	        'title'=> 'require',
	        'ex_title'   => 'require'
	        ];
	    $msg = [
	        'title.require' => '名称必须',
	        'ex_title.require'=> '副标题必须'
	        ];
	    $validate = new \think\Validate($rule,$msg);
	    $result   = $validate->batch()->check($data);
	    if(!$result){
	        return $validate->getError();
	        }
	    
	}
	public function upload($file_input_name){
	    $Config=array(
	        'size'=>3145728,
	        'ext'=>array('jpg', 'gif', 'png', 'jpeg')
	    );
	    $file=request()->file($file_input_name);
	    foreach($file as $k=>$v){
	        $info=$v->validate($Config)->move(ROOT_PATH . 'public' . DS . 'uploads');
	        if($info){
	            $y[]='public' . DS . 'uploads\\'.$info->getSaveName();
	            pr($y);die;
	            $this->thumb_save_name[]=$info->getFilename();
	            
	        }else{
	            $error['photo'][]=$v->getError();
	            $this->assign('error',$error);
	        }
	    }
	    return $y;
	}
	public function be_thumb($img_path,$width=150,$height=150,$thumb_save='./public/uploads/thumbs/',$type_code=1){
	    //文件夹不存在就创建
	    if(!file_exists($thumb_save))  mkdir($thumb_save);
	    
	    if(!$this->thumb_save_name){
	        
	        foreach($img_path as $k=>$v){
	            $image= \think\Image::open($v);
	            $this->img_width=$image->width();
	            $this->img_height=$image->height();
	            $v_arr=explode('\\',$v);
	            $name=$v_arr[count($v_arr)-1];
	            $thumb_save_path=$thumb_save.$name;
	            
	            $image->thumb($width,$height,$type_code)->save($thumb_save_path);
	            $thumb_save_path_array[$k]=$thumb_save_path;
	        }
	        
	    }else{
	    
	    foreach($this->thumb_save_name as $k=>$v){
	        //pr($img_path[$k]);exit;
	        $image= \think\Image::open($img_path[$k]);
	        
	        $thumb_save_path=$thumb_save.$v;
	        
	        $image->thumb($width,$height,$type_code)->save($thumb_save_path);
	        $thumb_save_path_array[$k]=$thumb_save_path;
	    }
	}
	    $this->thumb_save_name='';
	    return $thumb_save_path_array;
	}
	
	 
}